<template>
  <el-form
    v-if="listData.length"
    ref="forms"
    v-loading="loading"
    class="lookform"
    :label-position="labelPosition"
    :disabled="from==='audit'"
    :label-width="labelWidth"
    :model="formData"
  >
    <template v-if="departmentModel&&departmentModel.tem_content">
      <template v-for="(item, index) in departmentModel.tem_content.label_info">
        <el-form-item
          :key="item.time_unix"
          :label="item.label_key+'：'"
          :prop="item.time_unix"
          :rules="[{ required: item.if_required?true:false, message: `请输入${item.label_key}`, trigger: 'blur' },{ pattern: item.if_required?'[^ \x22]+':'', message: '不能输入纯空格', trigger: 'blur' }]"
        >
          <el-input
            v-if="item.label_type=='text'"
            v-model="formData[item.time_unix]"
            :disabled="formDisabled"
            type="text"
            :placeholder="'请输入'+item.label_key"
          />
          <el-input
            v-else-if="item.label_type=='textarea'"
            v-model="formData[item.time_unix]"
            :disabled="formDisabled"
            type="textarea"
            :placeholder="'请输入'+item.label_key"
            :autosize="{ minRows: 1, maxRows: 5}"
          />
          <vue-wangeditor
            v-else-if="item.label_type=='richtext'"
            :id="'editor'+item.time_unix"
            :ref="'editor'+item.time_unix"
            :value="formData[item.time_unix]"
            :menus="editMenu"
            :menu-fixed="false"
            width="100%"
            height="260"
            class="my-wangeditor"
            style="width: 100%;"
            @change="editChange(item.time_unix, index)"
          />
        </el-form-item>
      </template>
    </template>
    <el-form-item label="附件：">
      <file-preview
        v-if="formDisabled"
        :file-list="enclosure"
      />
      <upload
        v-else
        ref="upload"
        btn-type="text"
        szie="medium"
        :edit-list="enclosure"
        :project-data="{project_id: 'lookInfo',validation: 1}"
        @uploadSuccess="uploadSuccess"
        @deleteSuccess="deleteSuccess"
      />
    </el-form-item>
    <el-form-item v-if="!formDisabled&&from!=='audit'&&isJoin">
      <el-button
        plain
        @click="saveForm('forms')"
      >保存</el-button>
      <el-button
        type="primary"
        @click="submitForm('forms')"
      >提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { lookInfoModelList } from '@/api/lookInfoModel'
import { saveLookInfo } from '@/api/projectInformation'
import vueWangeditor from 'vue-wangeditor'
export default {
  components: {
    vueWangeditor
  },
  props: {
    projectId: {
      type: String,
      default: () => {}
    },
    labelPosition: {
      type: String,
      default: 'right'
    },
    labelWidth: {
      type: String,
      default: '160px'
    },
    // 当前登录人所在部门的id,name
    departmentData: {
      type: Object,
      default: () => {}
    },
    // 当前部门的调研报告信息
    departmentLookInfo: {
      type: Object,
      default: null
    },
    // 参与调研的部门模板列表
    listData: {
      type: Array,
      default: () => {}
    },
    from: {
      type: String,
      default: ''
    },
    isJoin: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      userInfo: null,
      loading: false,
      total: 0,
      // listData: [],
      departmentModel: {},
      formData: {},
      enclosure: [],
      formDisabled: false,
      queryParams: {
        pager: {
          limit: 20,
          skip: 1,
          order_by: '',
          OrderMethod: -1
        }
      },
      editMenu: [
        'bold', // 粗体
        'underline', // 下划线
        'italic', // 斜体
        'strikethrough', // 中线
        'eraser', // 清空格式
        'forecolor', // 文字颜色
        'bgcolor', // 背景颜色
        '|',
        'quote', // 引用
        'fontfamily', // 字体
        'fontsize', // 字号
        'head', // 标题
        // 'unorderlist', // 无序列表
        // 'orderlist', // 有序列表
        'alignleft', // 左对齐
        'aligncenter', // 居中
        'alignright' // 右对齐
      ]
    }
  },
  watch: {
    departmentLookInfo: {
      handler(newval, oldval) {
        if (newval && newval.if_commit === 1) {
          this.formDisabled = true
        } else {
          this.formDisabled = false
        }
        if (newval && newval.enclosure && newval.enclosure.length) {
          this.enclosure = newval.enclosure
        } else {
          this.enclosure = []
        }
      },
      deep: true,
      immediate: true
    },
    // 如果部门改变
    departmentData: {
      handler(newval, oldval) {
        console.log(2142)
        // 筛选出登陆者所在部门
        const currentData = this.listData.filter(
          (p) => p.department_id === newval.department_id
        )
        this.departmentModel = currentData[0] || []
        // 构造表单绑定数据以及表单校验
        if (this.departmentLookInfo) {
          this.mapFormData(this.departmentLookInfo.tem_content.label_info || [])
        } else {
          this.mapFormData(this.departmentModel.tem_content.label_info || [])
        }
        if (
          this.departmentLookInfo &&
          this.departmentLookInfo.enclosure.length
        ) {
          this.enclosure = this.departmentLookInfo.enclosure
        }
      }
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    this.userInfo = this.$store.getters.userInfo
    // this.getLookInfoModelList()
    // 筛选出登陆者所在部门
    const currentData = this.listData.filter(
      (p) => p.department_id === this.departmentData.department_id
    )
    this.departmentModel = this.departmentLookInfo || currentData[0]
    // 构造表单绑定数据以及表单校验
    if (this.departmentLookInfo) {
      this.mapFormData(this.departmentLookInfo.tem_content.label_info || [])
    } else {
      this.mapFormData(this.departmentModel.tem_content.label_info || [])
    }
  },
  methods: {
    deleteSuccess() {
      this.enclosure = this.$refs.upload.emitFileList()
    },
    uploadSuccess() {
      this.enclosure = this.$refs.upload.emitFileList()
    },
    mapFormData(list) {
      list.forEach((itm, idx) => {
        this.$set(this.formData, itm.time_unix, itm.label_value)
      })
    },
    mapSubmitData() {
      this.departmentModel.enclosure = this.enclosure
      console.log(this.departmentModel)
      for (const key in this.formData) {
        this.departmentModel.tem_content.label_info.forEach((itms, idxs) => {
          if (key === itms.time_unix) {
            itms.label_value = this.formData[key]
          }
        })
      }
    },
    // 部门尽调信息保存
    submitLookInfo(types) {
      let tip = ''
      if (types === 0) {
        this.departmentModel.if_commit = 0
        tip = '保存成功'
      } else if (types === 1) {
        this.departmentModel.if_commit = 1
        tip = '提交成功'
      }
      const datas = {
        id: this.projectId,
        research_info: this.departmentModel
      }
      saveLookInfo(datas).then((res) => {
        if (res.code === 200) {
          this.$emit('lookInfoSuccess')
          this.$message({
            type: 'success',
            message: tip
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    submitForm(formName) {
      const that = this
      // 赋值给模板
      this.mapSubmitData()
      console.log(this.formData, this.departmentModel)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.submitLookInfo(1)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveForm(formName) {
      const that = this
      // 赋值给模板
      this.mapSubmitData()
      console.log(this.formData, this.departmentModel)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.submitLookInfo(0)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    editChange(time_unix, index) {
      var ref = 'editor' + time_unix
      var content = this.$refs[ref][0].getHtml()
      this.$set(this.formData, time_unix, content)
      // this.$set(
      //   this.departmentModel.tem_content.label_info[index],
      //   'label_value',
      //   content
      // )
      console.log(
        time_unix,
        this.formData,
        this.departmentModel.tem_content.label_info,
        content
      )
    }
  }
}
</script>
<style lang="scss">
/* @import url(); 引入css类 */
.lookform {
  .my-wangeditor {
    p {
      margin: 0px !important;
    }
    margin-bottom: 5px !important;
    .wangEditor-container {
      display: flex;
      flex-direction: column;
      .wangEditor-txt {
        height: 228px !important;
        margin-top: 0px !important;
      }
      ul {
        li {
          list-style: disc !important;
        }
      }
      ol {
        li {
          list-style: decimal !important;
        }
      }
    }
  }
}
</style>
